#define  _CRT_SECURE_NO_WARNINGS
#include "SeqList.h"

void SeqListInit(SeqList* ps)
{
	assert(ps);
	ps->a = (SeqListDateType*)malloc(sizeof(SeqListDateType) * InitListSize);
	if (!ps->a)
	{
		perror("SeqListInit::malloc");
		return;
	}
	ps->capacity = InitListSize;
	ps->size = 0;
}

void SeqListDestroy(SeqList* ps)
{
	assert(ps);
	if (ps->capacity == 0)return;
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->size = 0;
}

void SeqListPrint(const SeqList* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

void SeqListPushBack(SeqList* ps, SeqListDateType x)
{
	assert(ps);
	SeqListInsert(ps, ps->size, x);
}

void SeqListPushFront(SeqList* ps, SeqListDateType x)
{
	assert(ps);
	SeqListInsert(ps, 0, x);
}

void SeqListPopFront(SeqList* ps)
{
	assert(ps);
	SeqListErase(ps, 0);
}

void SeqListPopBack(SeqList* ps)
{
	assert(ps);
	SeqListErase(ps, ps->size-1);
}

int SeqListFind(const SeqList* ps, SeqListDateType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void CheckCapacity(SeqList* ps)
{
	if (ps->capacity == ps->size)
	{
		ps->capacity *= 2;
		SeqListDateType* tmp = (SeqListDateType*)realloc(ps->a, sizeof(SeqListDateType) * ps->capacity);
		if (tmp == NULL)
		{
			perror("CheckCapacity::realloc");
			return;
		}
		ps->a = tmp;
	}
}

void SeqListInsert(SeqList* ps, int pos, SeqListDateType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	CheckCapacity(ps);
	memmove(ps->a + pos + 1, ps->a + pos, sizeof(SeqListDateType) * (ps->size - pos));
	ps->a[pos] = x;
	ps->size++;
}

void SeqListErase(SeqList* ps, int pos)
{
	assert(ps);
	assert(ps->size > 0);
	assert(pos >= 0 && pos < ps->size);
	memmove(ps->a + pos, ps->a + pos + 1, sizeof(SeqListDateType) * (ps->size - pos - 1));
	ps->size--;
}